home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / os.py < prev    next >
Text File  |  1999-06-14  |  8KB  |  272 lines

  1. # os.py -- either mac, dos or posix depending on what system we're on.
  2.  
  3. # This exports:
  4. # - all functions from either posix or mac or amiga, e.g., os.unlink, os.stat, etc.
  5. # - os.path is either module posixpath or macpath or amigapath
  6. # - os.name is either 'posix' or 'mac' or 'amiga'
  7. # - os.curdir is a string representing the current directory ('.' or ':' or '')
  8. # - os.pardir is a string representing the parent directory ('..' or '::' or '/')
  9. # - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
  10. # - os.altsep is the alternatte pathname separator (None or '/')
  11. # - os.pathsep is the component separator used in $PATH etc
  12. # - os.defpath is the default search path for executables
  13.  
  14. # Programs that import and use 'os' stand a better chance of being
  15. # portable between different platforms.  Of course, they must then
  16. # only use functions that are defined by all platforms (e.g., unlink
  17. # and opendir), and leave all pathname manipulation to os.path
  18. # (e.g., split and join).
  19.  
  20. import sys
  21.  
  22. _names = sys.builtin_module_names
  23.  
  24. altsep = None
  25.  
  26. if 'posix' in _names:
  27.     name = 'posix'
  28.     linesep = '\n'
  29.     curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':'
  30.     defpath = ':/bin:/usr/bin'
  31.     from posix import *
  32.     try:
  33.         from posix import _exit
  34.     except ImportError:
  35.         pass
  36.     import posixpath
  37.     path = posixpath
  38.     del posixpath
  39. elif 'amiga' in _names:
  40.     name = 'amiga'
  41.     linesep = '\n'
  42.     curdir = ''; pardir = '/'; sep = '/'; pathsep = ';'
  43.     defpath = 'C:'
  44.     from amiga import *
  45.     try:
  46.         from amiga import _exit
  47.     except ImportError:
  48.         pass
  49.     import amigapath
  50.     path = amigapath
  51.     del amigapath
  52. elif 'nt' in _names:
  53.     name = 'nt'
  54.     linesep = '\r\n'
  55.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  56.     defpath = '.;C:\\bin'
  57.     from nt import *
  58.     for i in ['_exit']:
  59.         try:
  60.             exec "from nt import " + i
  61.         except ImportError:
  62.             pass
  63.     import ntpath
  64.     path = ntpath
  65.     del ntpath
  66. elif 'dos' in _names:
  67.     name = 'dos'
  68.     linesep = '\r\n'
  69.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  70.     defpath = '.;C:\\bin'
  71.     from dos import *
  72.     try:
  73.         from dos import _exit
  74.     except ImportError:
  75.         pass
  76.     import dospath
  77.     path = dospath
  78.     del dospath
  79. elif 'os2' in _names:
  80.     name = 'os2'
  81.     linesep = '\r\n'
  82.     curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
  83.     defpath = '.;C:\\bin'
  84.     from os2 import *
  85.     try:
  86.         from os2 import _exit
  87.     except ImportError:
  88.         pass
  89.     import ntpath
  90.     path = ntpath
  91.     del ntpath
  92. elif 'mac' in _names:
  93.     name = 'mac'
  94.     linesep = '\r'
  95.     curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
  96.     defpath = ':'
  97.     from mac import *
  98.     try:
  99.         from mac import _exit
  100.     except ImportError:
  101.         pass
  102.     import macpath
  103.     path = macpath
  104.     del macpath
  105. else:
  106.     raise ImportError, 'no os specific module found'
  107.  
  108. del _names
  109.  
  110. sys.modules['os.path'] = path
  111.  
  112. # Super directory utilities.
  113. # (Inspired by Eric Raymond; the doc strings are mostly his)
  114.  
  115. def makedirs(name, mode=0777):
  116.     """makedirs(path [, mode=0777]) -> None
  117.  
  118.     Super-mkdir; create a leaf directory and all intermediate ones.
  119.     Works like mkdir, except that any intermediate path segment (not
  120.     just the rightmost) will be created if it does not exist.  This is
  121.     recursive.
  122.  
  123.     """
  124.     head, tail = path.split(name)
  125.     if head and tail and not path.exists(head):
  126.         makedirs(head, mode)
  127.     mkdir(name, mode)
  128.  
  129. def removedirs(name):
  130.     """removedirs(path) -> None
  131.  
  132.     Super-rmdir; remove a leaf directory and empty all intermediate
  133.     ones.  Works like rmdir except that, if the leaf directory is
  134.     successfully removed, directories corresponding to rightmost path
  135.     segments will be pruned way until either the whole path is
  136.     consumed or an error occurs.  Errors during this latter phase are
  137.     ignored -- they generally mean that a directory was not empty.
  138.  
  139.     """
  140.     rmdir(name)
  141.     head, tail = path.split(name)
  142.     while head and tail:
  143.         try:
  144.             rmdir(head)
  145.         except error:
  146.             break
  147.         head, tail = path.split(head)
  148.  
  149. def renames(old, new):
  150.     """renames(old, new) -> None
  151.  
  152.     Super-rename; create directories as necessary and delete any left
  153.     empty.  Works like rename, except creation of any intermediate
  154.     directories needed to make the new pathname good is attempted
  155.     first.  After the rename, directories corresponding to rightmost
  156.     path segments of the old name will be pruned way until either the
  157.     whole path is consumed or a nonempty directory is found.
  158.  
  159.     Note: this function can fail with the new directory structure made
  160.     if you lack permissions needed to unlink the leaf directory or
  161.     file.
  162.  
  163.     """
  164.     head, tail = path.split(new)
  165.     if head and tail and not path.exists(head):
  166.         makedirs(head)
  167.     rename(old, new)
  168.     head, tail = path.split(old)
  169.     if head and tail:
  170.         try:
  171.             removedirs(head)
  172.         except error:
  173.             pass
  174.  
  175. # Make sure os.environ exists, at least
  176. try:
  177.     environ
  178. except NameError:
  179.     environ = {}
  180.  
  181. def execl(file, *args):
  182.     execv(file, args)
  183.  
  184. def execle(file, *args):
  185.     env = args[-1]
  186.     execve(file, args[:-1], env)
  187.  
  188. def execlp(file, *args):
  189.     execvp(file, args)
  190.  
  191. def execlpe(file, *args):
  192.     env = args[-1]
  193.     execvpe(file, args[:-1], env)
  194.  
  195. def execvp(file, args):
  196.     _execvpe(file, args)
  197.  
  198. def execvpe(file, args, env):
  199.     _execvpe(file, args, env)
  200.  
  201. _notfound = None
  202. def _execvpe(file, args, env = None):
  203.     if env:
  204.         func = execve
  205.         argrest = (args, env)
  206.     else:
  207.         func = execv
  208.         argrest = (args,)
  209.         env = environ
  210.     global _notfound
  211.     head, tail = path.split(file)
  212.     if head:
  213.         apply(func, (file,) + argrest)
  214.         return
  215.     if env.has_key('PATH'):
  216.         envpath = env['PATH']
  217.     else:
  218.         envpath = defpath
  219.     import string
  220.     PATH = string.splitfields(envpath, pathsep)
  221.     if not _notfound:
  222.         import tempfile
  223.         # Exec a file that is guaranteed not to exist
  224.         try: execv(tempfile.mktemp(), ())
  225.         except error, _notfound: pass
  226.     exc, arg = error, _notfound
  227.     for dir in PATH:
  228.         fullname = path.join(dir, file)
  229.         try:
  230.             apply(func, (fullname,) + argrest)
  231.         except error, (errno, msg):
  232.             if errno != arg[0]:
  233.                 exc, arg = error, (errno, msg)
  234.     raise exc, arg
  235.  
  236. # Change environ to automatically call putenv() if it exists
  237. try:
  238.     # This will fail if there's no putenv
  239.     putenv
  240. except NameError:
  241.     pass
  242. else:
  243.     import UserDict
  244.  
  245.     if name in ('os2', 'nt', 'dos'):  # Where Env Var Names Must Be UPPERCASE
  246.         # But we store them as upper case
  247.         import string
  248.         class _Environ(UserDict.UserDict):
  249.             def __init__(self, environ):
  250.                 UserDict.UserDict.__init__(self)
  251.                 data = self.data
  252.                 upper = string.upper
  253.                 for k, v in environ.items():
  254.                     data[upper(k)] = v
  255.             def __setitem__(self, key, item):
  256.                 putenv(key, item)
  257.                 key = string.upper(key)
  258.                 self.data[key] = item
  259.             def __getitem__(self, key):
  260.                 return self.data[string.upper(key)]
  261.  
  262.     else:  # Where Env Var Names Can Be Mixed Case
  263.         class _Environ(UserDict.UserDict):
  264.             def __init__(self, environ):
  265.                 UserDict.UserDict.__init__(self)
  266.                 self.data = environ
  267.             def __setitem__(self, key, item):
  268.                 putenv(key, item)
  269.                 self.data[key] = item
  270.  
  271.     environ = _Environ(environ)
  272.